package com.zoe.onelink.business.mybatis.typehandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.io.ByteArrayInputStream;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * <p>标题: mapper中blob转化</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2019</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: chenweibin
 * @date 2020/2/13
 */
@MappedJdbcTypes(JdbcType.BLOB)
@MappedTypes(String.class)
public class BlobToStringTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
//        preparedStatement.setString(i, s);
        ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
        preparedStatement.setBinaryStream(i, is, s.getBytes().length);
    }

    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        Blob blob = resultSet.getBlob(s);
        String result = getString(blob);
        return result;
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        Blob blob = resultSet.getBlob(i);
        String result = getString(blob);
        return result;
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        Blob blob = callableStatement.getBlob(i);
        String result = getString(blob);
        return result;
    }

    private String getString(Blob blob) throws SQLException {
        byte[] returnValue = null;
        String result = null;
        if (null != blob) {
            returnValue = blob.getBytes(1, (int) blob.length());
        }
        //将取出的流对象转为utf-8的字符串对象
        if (null != returnValue) {
            result = new String(returnValue);
        }
        return result;
    }
}
